//=============================================================
// 创建人:            ssd
// 创建时间:          8/8/2024 12:30:10 AM
// 邮箱：             1292934053@qq.com
//==============================================================
using System.Reflection;
using System.Reflection.Emit;
using LF.Common;
using LF.Domain.Entities;
using LF.Domain.Helper;
using static LF.Common.AppConfig;
using LF.Domain.Services;

namespace LF.Domain.Services.Iml
{
    public class UserManagerService : IUserManagerService
    {
        private readonly IDeptmentManagerService _deptmentManager;

        public UserManagerService(IDeptmentManagerService deptmentManager)
        {
            _deptmentManager = deptmentManager;
        }

        public bool Actived(Guid id)
        {
            var result = FreeSqlHelper.DbContext.Update<User>(id).Set(p => p.Active, true).ExecuteAffrows();
            return result > 0;
        }

        public bool AddRoles(List<UserRole> roles)
        {
            var result = FreeSqlHelper.DbContext.Insert(roles).ExecuteAffrows();
            return result > 0;
        }

        public List<User> All(int index, int pageSize, string? key, string? deptId)
        {
            var query = FreeSqlHelper.DbContext.Queryable<User>()
                .LeftJoin<Deptment>((u, d) => u.DeptId == d.Id)
                .IncludeMany(u => u.UserRoles, then => then.Include(ur => ur.Role))
                .Where(p => !p.IsDelete);
            
            if (!key.IsNullOrWhiteSpace())
            {
                query = query.Where(p => p.RealName.Contains(key!)
                || p.UserName.Contains(key!));
            }
            
            if (!deptId.IsNullOrWhiteSpace())
            {
                // 尝试解析部门ID
                if (Guid.TryParse(deptId, out Guid deptGuid))
                {
                    // 获取指定部门及其所有子部门
                    var deptWithChildren = _deptmentManager.GetDeptWithChildren(deptGuid);
                    var deptIds = deptWithChildren.Select(d => d.Id).ToList();
                    
                    // 查询属于这些部门的用户
                    query = query.Where(p => p.DeptId.HasValue && deptIds.Contains(p.DeptId.Value));
                }
                else
                {
                    // 如果无法解析为Guid，则按原逻辑处理
                    query = query.Where(p => p.DeptId.ToString() == deptId);
                }
            }
            
            var list = query
                .OrderByDescending(p => p.UpdateTime)
                .Page(index, pageSize)
                .ToList();
            
            return list;
        }

        public List<User> GetAllUsers(string? key = null, string? deptId = null)
        {
            var query = FreeSqlHelper.DbContext.Queryable<User>()
                .LeftJoin<Deptment>((u, d) => u.DeptId == d.Id)
                .IncludeMany(u => u.UserRoles, then => then.Include(ur => ur.Role))
                .Where(p => !p.IsDelete);
            
            if (!key.IsNullOrWhiteSpace())
            {
                query = query.Where(p => p.RealName.Contains(key!)
                || p.UserName.Contains(key!));
            }
            
            if (!deptId.IsNullOrWhiteSpace())
            {
                // 尝试解析部门ID
                if (Guid.TryParse(deptId, out Guid deptGuid))
                {
                    // 获取指定部门及其所有子部门
                    var deptWithChildren = _deptmentManager.GetDeptWithChildren(deptGuid);
                    var deptIds = deptWithChildren.Select(d => d.Id).ToList();
                    
                    // 查询属于这些部门的用户
                    query = query.Where(p => p.DeptId.HasValue && deptIds.Contains(p.DeptId.Value));
                }
                else
                {
                    // 如果无法解析为Guid，则按原逻辑处理
                    query = query.Where(p => p.DeptId.ToString() == deptId);
                }
            }
            
            var list = query
                .OrderByDescending(p => p.UpdateTime)
                .ToList();
            
            return list;
        }

        public bool ClearRoles(Guid id)
        {
            var result = FreeSqlHelper.DbContext.Delete<UserRole>(new {UserId = id}).ExecuteAffrows();
            return result > 0;
        }

        public long Count(string? key, string? deptId = null)
        {
            var query = FreeSqlHelper.DbContext.Queryable<User>().Where(p => !p.IsDelete);
            
            if (!key.IsNullOrWhiteSpace())
            {
                query = query.Where(p => p.RealName.Contains(key!)
                || p.UserName.Contains(key!));
            }
            
            if (!deptId.IsNullOrWhiteSpace())
            {
                // 尝试解析部门ID
                if (Guid.TryParse(deptId, out Guid deptGuid))
                {
                    // 获取指定部门及其所有子部门
                    var deptWithChildren = _deptmentManager.GetDeptWithChildren(deptGuid);
                    var deptIds = deptWithChildren.Select(d => d.Id).ToList();
                    
                    // 查询属于这些部门的用户
                    query = query.Where(p => p.DeptId.HasValue && deptIds.Contains(p.DeptId.Value));
                }
                else
                {
                    // 如果无法解析为Guid，则按原逻辑处理
                    query = query.Where(p => p.DeptId.ToString() == deptId);
                }
            }
            
            var count = query.Count();
            return count;
        }

        public bool Disabled(Guid id)
        {
            var result = FreeSqlHelper.DbContext.Update<User>(id).Set(p => p.Active, false).ExecuteAffrows();
            return result > 0;
        }
        
        public User GetUserByOpenId(string openId)
        {
            var item = FreeSqlHelper.DbContext.Queryable<User>().Where(p => p.OpenId == openId).First();
            return item;
        }

        public User GetUserByQyWeixinId(string qyWeixinUserId)
        {
            var item = FreeSqlHelper.DbContext.Queryable<User>().Where(p => p.QyWeixinUserId == qyWeixinUserId).First();
            return item;
        }
        public User Get(Guid id)
        {
            var item = FreeSqlHelper.DbContext.Queryable<User>()
                .LeftJoin<Deptment>((u, d) => u.DeptId == d.Id)
                .IncludeMany(u => u.UserRoles, then => then.Include(ur => ur.Role))
                .Where(p => p.Id == id)
                .First();
            return item;
        }

        public bool Insert(User user)
        {
            var result = FreeSqlHelper.DbContext.Insert(user).ExecuteAffrows();
            return result > 0;
        }

        public List<RoleMenu> Menus(Guid id)
        {
            var roles = FreeSqlHelper.DbContext.Queryable<UserRole>().Where(p => p.UserId == id).ToList(p => p.RoleId);
            var menus = FreeSqlHelper.DbContext.Queryable<RoleMenu>().Where(p => roles.Contains(p.RoleId)).ToList();
            return menus;
        }

        public bool RealDelete(Guid id)
        {
            var result = FreeSqlHelper.DbContext.Delete<User>(id).ExecuteAffrows();
            return result > 0;
        }

        public bool Delete(Guid[] ids)
        {
            var result = FreeSqlHelper.DbContext.Update<User>()
                .Set(p => p.IsDelete == true)
                .Where(p=>ids.Contains(p.Id))
                .ExecuteAffrows();
            return result > 0;
        }

        public bool ResetPwd(Guid id, string pwd)
        {
            var result = FreeSqlHelper.DbContext.Update<User>(id)
             .Set(p => p.Password == pwd)
             .ExecuteAffrows();
            return result > 0;
        }

        public bool ChangePassword(Guid id, string oldPassword, string newPassword)
        {
            // 先获取用户，验证旧密码是否正确
            var user = FreeSqlHelper.DbContext.Select<User>()
                .Where(p => p.Id == id)
                .First();
                
            if (user == null || user.Password != oldPassword)
            {
                return false; // 用户不存在或旧密码不正确
            }
            
            // 旧密码验证成功，更新新密码
            var result = FreeSqlHelper.DbContext.Update<User>(id)
                .Set(p => p.Password == newPassword)
                .ExecuteAffrows();
                
            return result > 0;
        }

        public List<UserRole> Roles(Guid id)
        {
            var query = FreeSqlHelper.DbContext.Queryable<UserRole>();
            var list = query.Where(p => p.UserId == id)
                .ToList();
            return list;
        }

        public bool Update(User user)
        {
            var result = FreeSqlHelper.DbContext.Update<User>(user.Id)
               .SetSource(user)
               .ExecuteAffrows();
            return result > 0;
        }

        public bool CheckUser(string openId, string usercode)
        {
            var result = FreeSqlHelper.DbContext.Queryable<User>()
                .Where(p => p.OpenId == openId || p.UserCode == usercode).Any();
            return result;
        }
    }
}

